//
//  ModifyTelephoneVC.m
//  wanzhaoIM
//
//  Created by liuyuantao on 15/5/8.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "ModifyTelephoneVC.h"
#import "MicroDef.h"
#import "JKAlertDialog.h"
//#import "CXmppMgr.h"
#import "CXmppRequestMgr.h"
#import "UIUtil.h"
#import "MBProgressHUD+WZ.h"
#import "UIBarButtonItem+category.h"

@interface ModifyTelephoneVC ()<UITextViewDelegate>
{
    UITextView *_messageTextView;
}
@end

@implementation ModifyTelephoneVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationItem setNewTitleCenter:self.title];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"call_back" title:@"返回" target:self sel:@selector(back) titleFont:Font18 titleColor:WhiteColor];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:nil title:@"保存" target:self sel:@selector(save) titleFont:Font18 titleColor:WhiteColor];
    
    // Do any additional setup after loading the view.
    if (self.vc_type.integerValue == 0) {
        [self.navigationItem setNewTitleCenter:@"修改座机号码"];
    } else if (self.vc_type.integerValue == 1) {
        [self.navigationItem setNewTitleCenter:@"修改手机号码"];
    } else {
        [self.navigationItem setNewTitleCenter:@"修改邮箱地址"];
    }
    
    UIView *superView = self.view;
    _messageTextView = [[UITextView alloc] init];
    [superView addSubview:_messageTextView];
    
    if (self.vc_type.integerValue == 0) {
        _messageTextView.text = self.curUser.EXtenSion;
        
    } else if (self.vc_type.integerValue == 1) {
        _messageTextView.text = self.curUser.MobileTelephone;
    } else {
        _messageTextView.text = self.curUser.Email;
    }
    
     NSString *string = [[NSString alloc]init];
     string = _messageTextView.text;
    
     [_messageTextView setAutocorrectionType:UITextAutocorrectionTypeNo];
     [_messageTextView setReturnKeyType:UIReturnKeyGo];
     [_messageTextView.layer setCornerRadius:6.0f];
     [_messageTextView setSelectedRange:NSMakeRange(string.length,0)];
     _messageTextView.delegate = self;
     [_messageTextView setFont:[UIFont systemFontOfSize:18.0f]];
     [_messageTextView setTextColor:RGBCOLOR(0x32, 0x32, 0x32)];
     _messageTextView.layer.cornerRadius = 5.0f/2;
     _messageTextView.layer.masksToBounds = YES;
     _messageTextView.layer.borderWidth = 0.5f;
     _messageTextView.layer.borderColor = RGBCOLOR(0xd4, 0xd4, 0xd4).CGColor;
     [self.view addSubview:_messageTextView];
    
    CGFloat padding = 10.0f;
    CGFloat hight = 100.0f;
    if(HARDWARE_SCREEN_HEIGHT >= 736)
    {
        hight = 700.0f/3.0f;
    }
    _messageTextView.frame = CGRectMake(padding, padding, HARDWARE_SCREEN_WIDTH - 2 * padding, hight);
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveSuccess:) name:K_XMPPMODIFYINFO object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveFailed) name:K_XMPPDIDFAILEDRECEIVEIQ object:nil];

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPDIDFAILEDRECEIVEIQ object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPMODIFYINFO object:nil];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_messageTextView resignFirstResponder];
}


-(void)back
{
    
//    switch (self.vc_type.integerValue) {
//        case 0:
//        {
//            if ([self.curUser.EXtenSion isEqualToString:_inputTX.text]) {
//                [self.navigationController popViewControllerAnimated:YES ];
//            } else {
//                
//            }
//        }
//            break;
//        case 1:
//        {
//            if ([self.curUser.MobileTelephone isEqualToString:_inputTX.text]) {
//                [self.navigationController popViewControllerAnimated:YES ];
//            } else {
//                
//            }
//        }
//            break;
//        case 2:
//        {
//            if ([self.curUser.EXtenSion isEqualToString:_inputTX.text]) {
//                [self.navigationController popViewControllerAnimated:YES ];
//            } else {
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"您修改的信息是否需要保存" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//                [alert show];
//            }
//
//        }
//            break;
//            
//        default:
//            break;
//    }

//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"您修改的信息是否需要保存" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//    [alert show];
    
    
    [_messageTextView endEditing:YES];
    
    switch (self.vc_type.integerValue) {
        case 0:
        {
            if ([self.curUser.Telephone isEqualToString:_messageTextView.text]) {
                [self.navigationController popViewControllerAnimated:YES];
                return;
            }
        }
            break;
        case 1:
        {
            if ([self.curUser.MobileTelephone isEqualToString:_messageTextView.text]) {
                [self.navigationController popViewControllerAnimated:YES];
                return;
            }

        }
            break;
        case 2:
        {
            if ([self.curUser.Email isEqualToString:_messageTextView.text]) {
                [self.navigationController popViewControllerAnimated:YES];
                return;
            }

        }
            break;
            
        default:
            break;
    }

    __block ModifyTelephoneVC *block = self;
    JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:@"您修改的信息是否需要保存"];
    [alert addButton:Button_OK withTitle:@"是" handler:^(JKAlertDialogItem *item) {
        
        [block save];
        
            }];
    
    [alert addButton:Button_CANCEL withTitle:@"否" handler:^(JKAlertDialogItem *item) {
        
        [block.navigationController popViewControllerAnimated:YES ];
    }];
    [alert show];

    
}

//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    switch (buttonIndex) {
//        case 0:
//        {
//            [self.navigationController popViewControllerAnimated:YES ];
//        }
//            break;
//        case 1:
//        {
//            [self save];
//        }
//            break;
//        default:
//            break;
//    }
//}

#pragma mark 通知中心方法
- (void)saveSuccess:(NSNotification *)notice
{
    [UIUtil hideMBProgressViewForView:self.view];
    switch (self.vc_type.integerValue) {
        case 0:
        {
            self.curUser.Telephone = _messageTextView.text;
        }
            break;
        case 1:
        {
            self.curUser.MobileTelephone = _messageTextView.text;
        }
            break;
        case 2:
        {
            self.curUser.Email = _messageTextView.text;
        }
            break;
            
        default:
            break;
    }
    
    
    [MBProgressHUD showSuccess:@"保存成功"];
    
    [self.navigationController popViewControllerAnimated:YES ];
    

}

- (void)saveFailed
{
    [UIUtil hideMBProgressViewForView:self.view];
    [MBProgressHUD showError:@"保存失败，请您检查网络"];
    [self.navigationController popViewControllerAnimated:YES];
//    __block ModifyTelephoneVC *block = self;
//    JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"" message:@"保存失败"];
//    [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
//        [block.navigationController popViewControllerAnimated:YES ];
//        }];
//    [alert show];

    
}
-(void)save
{
    [_messageTextView resignFirstResponder];
    //bug 9469 fixed by lixu
    if (![UIUtil isNetworkReachable]){
        [MBProgressHUD showError:@"保存失败，请检查网络"];
        return;
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    BOOL result;
    switch (self.vc_type.integerValue) {
        case 0:
        {
            dict[@"telephone"] = _messageTextView.text;
            [[CXmppRequestMgr shareInstance] updateSingleUserInfoWithDic:dict];
            
            [UIUtil addMBProgressViewTitle:@"正在保存..." inView:self.view alpha:0.5 failureTitle:@"保存失败，请检查网络"];

        }
            break;
        case 1:
        {
            result = [self isValidateMobile:_messageTextView.text];
            if (result) {
                dict[@"mobilePhone"] = _messageTextView.text;
                [[CXmppRequestMgr shareInstance] updateSingleUserInfoWithDic:dict];
                
                [UIUtil addMBProgressViewTitle:@"正在保存..." inView:self.view alpha:0.5 failureTitle:@"保存失败，请检查网络"];
            } else {
//                JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"" message:@"您输入的手机号不合法"];
//                [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
//                            }];
//                [alert show];
                [MBProgressHUD showError:@"您输入的手机号码不对，请重新输入"];
            }
            
        }
            break;
        case 2:
        {
           result = [self isValidateEmail:_messageTextView.text];
            if (result) {
                dict[@"email"] = _messageTextView.text;
                [[CXmppRequestMgr shareInstance] updateSingleUserInfoWithDic:dict];
                
                [UIUtil addMBProgressViewTitle:@"正在保存..." inView:self.view alpha:0.5 failureTitle:@"保存失败，请检查网络"];

            } else {
//                JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"" message:@"您输入邮箱地址不合法"];
//                [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
//                }];
//                [alert show];
                [MBProgressHUD showError:@"请输入正确的邮箱地址"];

            }
            
        }
    }
    
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    switch (self.vc_type.integerValue) {
        case 0:
        {
            
        }
        case 1:{
            if ([text isEqualToString: @"\n"]) {
                // Hide the keyboard
                [textView resignFirstResponder];
                
                // Also return if its showing a placeholder
                return NO ;
            }
            if ([text isEqualToString:@""]) {
                return YES;
            }
            
            if (textView.text.length > 11) {
                return NO;
            }

        }
        case 2:{
            if ([text isEqualToString: @"\n"]) {
                // Hide the keyboard
                [textView resignFirstResponder];
                
                // Also return if its showing a placeholder
                return NO ;
            }
            if ([text isEqualToString:@""]) {
                return YES;
            }
            
            if (textView.text.length > 49) {
                return NO;
            }
            
        }
    }

    
    
    return YES ;
    
}


- (void)textViewDidChange:(UITextView *)textView
{
    switch (self.vc_type.integerValue) {
        case 0:
        {
            
        }
        case 1:{
            if (textView.text.length > 11) {
                
                textView.text = [textView.text substringToIndex:11];
                [MBProgressHUD showError:@"不能超过11个字符"];
            }

        }
        case 2:{
            
            if (textView.text.length > 50) {
                
                textView.text = [textView.text substringToIndex:50];
                [MBProgressHUD showError:@"不能超过50个字符"];
            }
            
        }
    }
}


-(BOOL)isValidateEmail:(NSString *)email {
    
    if (email.length > 0) {
        if (email.length > 50) {
            return NO;
        }
        NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
        return [emailTest evaluateWithObject:email];

    } else {
        _messageTextView.text = @"";
        return YES;
    }
}
-(BOOL) isValidateMobile:(NSString *)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    if (mobile.length > 0) {
        NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
        NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
        //    NSLog(@"phoneTest is %@",phoneTest);
        return [phoneTest evaluateWithObject:mobile];
    } else {
        _messageTextView.text = @"";
        return YES;
    }
   
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
